$(function () {
  const form = layui.form
  const layer = layui.layer
  form.render()
  const laypage = layui.laypage;
  let q = {
    advimgdesc: '', // 页码值，默认请求第一页的数据
    advimgpos: '', // 每页显示几条数据，默认每页显示2条
    page: 1, // 页码
    limit: 10 // 每页数量
  }



  function renderContent() {
    axios.get('/ydd_advimg/list').then(({ data: { data } }) => {
      const htmlStr = data.data.map(({ advimgdesc, advimglink, advimgpos, advimgsrc, advposname, default_data, id }, i) => {
        return `
          <tr>
            <td><input type="checkbox" name="" id="check" data-name="check"></td>
            <td>${i + 1}</td>
            <td>${advposname}</td>
            <td>${advimgdesc}</td>
            <td><img src="http://124.223.14.236:8060/${advimgsrc}" alt=""></td>
            <td>${advimglink}</td>
            <td>
              <button id="change" type="button" class="layui-btn layui-btn-normal layui-icon layui-icon-edit" style="border-radius: 50%;" data-id="${id}"></button>
              <button id="del" type="button" class="layui-btn layui-btn-danger layui-icon layui-icon-delete" style="border-radius: 50%;" data-id="${id}"></button>
            </td>
          </tr>
        `
      }).join('')

      $('#tbody').html(htmlStr)


      // 渲染分页
      renderPage()
    })
  }



  // 渲染分页
  function renderPage(count) {
    //执行一个laypage实例
    laypage.render({
      elem: 'page-box' //注意，这里的 test1 是 ID，不用加 # 号
      , count: count, //数据总数，从服务端得到
      curr: q.page,//当前接口请求的是哪一页
      // 每页显示条数
      limit: q.limit,
      layout: ['count', 'limit', 'prev', 'page', 'next'],
      limits: [5, 10, 15],
      jump: function (obj, first) {
        // console.log('first', first)
        // console.log('obj', obj)
        // curr当前页
        q.page = obj.curr
        q.limit = obj.limit
        // 首页不执行
        if (!first) {
          renderContent()
        }
      }
    });
  }

  renderContent()
  renderCate()


  let selectObj = {}
  function renderCate() {
    axios.get('/ydd_advpos/all').then(({ data }) => {
      if (data.errno) return layer.msg('获取失败')
      let str = '<option value=""></option>'
      data.data.forEach(({ advposdesc, advposname, advpossize, default_data, id }) => {

        selectObj[id] = advposname
        str += `<option value="${id}">${advposname}</option>`
      })
      $('.layui-form [name="state"]').html(str)
      selectIn = str
      form.render()
    })
  }



  // 搜索
  $('#selectForm').on('submit', function (e) {
    e.preventDefault()

    const advimgdesc = $('[name=advimgdesc]').val()
    const advimgpos = $('[name=state] :selected').val()

    q.advimgdesc = advimgdesc
    q.advimgpos = advimgpos
    renderContent()
  })

  //  重置
  $('#reload').on('click', function () {
    location.href = './advimg.html'
  })

  // 单选控制全选
  $('tbody').on('click', '#check', function () {
    // console.log(111);

    if ($('#check:checked').length === q.limit) {
      $('#checkall').prop('checked', true)
    } else {
      $('#checkall').prop('checked', false)
    }

  })

  // 全选控制单选
  $('#checkall').click(function () {
    // console.log(222);
    $('tbody #check').prop('checked', $(this).prop('checked'))
  })


  $('body').on('click', '#del', function () {
    const length = $('#del').length
    const id = String($(this).attr('data-id'))
    layer.confirm('确认删除', { icon: 3, title: '提示' }, function (index) {
      axios.get('/ydd_advimg/del?id=' + id).then(({ errno, errmsg }) => {
        if (errno) return layer.msg(errmsg)
        if (length === 1 && q.page > 1) {
          q.page -= 1
        }
        renderContent()
      })
    })
  })
  let img = ''
  // 添加
  let layerIndex = null

  $('body').on('click', '#change', function () {
    layerIndex = layer.open({
      // const layer = layui.layer;
      type: 1,
      area: ['500px', '300px'],
      title: '添加广告',
      content: $('#dialog-add').html()

    });
    $('#form-add [name="state"]').html(selectIn)
    form.render()

    // 上传图片清空图片
    $('#form-add .picLoad .layui-btn').on('click', function () {
      // console.log('删除');
      $('#form-add #show').attr('src', '')
      $('#form-add .picLoad').hide()
    })
    $('#form-add #upload').on('click', function (e) {
      e.preventDefault()
      $('#file').click()
    })
    $('body').on('change', '#form-add #file', function (e) {
      console.log(e);
      const files = e.target.files
      const imgUrl = window.URL.createObjectURL(files[0])

      document.getElementById('showAdd').src = imgUrl
      document.getElementById('showAdd').style = 'width: 190px;height: 100px;display:block;'


      let img1 = new FormData($('#form-add')[0])
      $.ajax({
        url: '/common/upload?type=images',
        method: 'POST',
        data: img1,
        contentType: false,
        processData: false,
        success: function (res) {
          // console.log(res);
          img = res.data.savePath
          $('#form-add .picLoad').show()
        }
      })

    })
  })


  // 确认添加
  $('#form-add .sure').on('click', function (e) {
    e.preventDefault()
    let picObj = {
      advimgdesc: $('#form-add #advimgdesc').val().trim(),
      advimglink: $('#form-add #advimglink').val().trim(),
      advimgpos: +$('#form-add .input1 :selected').val(),
      advimgsrc: img
    }
    $.ajax({
      method: 'POST',
      url: '/ydd_advimg/add',
      // headers:{
      //   'Content-Type':'multipart/form-data'
      // },
      data: picObj,
      success: function (res) {
        console.log(res);
        if (res.errno) return layer.msg(res.errmsg)
        layer.close(layerIndex)
        renderContent()
      }
    })
  })
  // 关闭添加框
  $('#form-add .out').on('click', function (e) {
    e.preventDefault()
    layer.close(layerIndex)
  })



  let imgChange = null
  let changeId = null
  // 修改广告
  let layerIndexChange = null
  $('tbody').on('click', '#change', function () {
    // console.log('change');
    layerIndexChange = layer.open({
      // const layer = layui.layer;
      type: 1,
      area: ['500px', '300px'],
      title: '修改广告',
      content: $('#dialog-change').html()
    });

  })


  // 渲染详情
  changeId = $(this).data('id')
  // console.log(changeId);
  $.ajax({
    method: 'GET',
    url: '/ydd_advimg/rowInfo',
    data: {
      id: changeId
    },
    success: function (res) {
      console.log(res);
      // if(!res.errno) return layer.msg(res.errmsg)
      const { data: { advimgdesc, advimglink, advimgpos, advimgsrc, id } } = res

      $('#form-change #input').html(selectIn)
      form.render()
      // console.log(123);
      $('#form-change #advimgdesc').val(advimgdesc)
      $('#form-change #advimglink').val(advimglink)
      // $('#form-change #show').css('display','block')
      $('#form-change #showChange').attr('src', `http://124.223.14.236:8060/${advimgsrc}`)
    }
  })


  // 清空图片
  $('#form-change .picLoad .layui-btn').on('click', function () {
    // console.log('删除');
    $('#form-change #show').attr('src', '')
    $('#form-change .picLoad').hide()
  })
  // 点击上传图片
  $('#form-change #upload').on('click', function (e) {
    e.preventDefault()
    $('#file').click()
  })

  

})